var app = getApp()
var util=require("../../lib/utils.js")
Page({
  data: {
    curImg: '',
    toImage: 'http://usr/0002.png',
    toPic: '',
    isHave: false,
    isInit: false,
    isBlackFirst:true,
    imgs: [],
    imageWidth: '',
    imageHeight: '',
    originalWidth: '',
    originalHeight: '',
    canvasWidth: '',
    canvasHeight: '',
    imgsBw: ["../../images/1.jpg", "../../images/2.jpg", "../../images/3.jpg"],
    imgsBlurry: ["../../images/4.jpg", "../../images/5.jpg", "../../images/6.jpg"],
    accessToken:'',
    mode:0,
    name:''
  },
  onLoad: function (options) {
    var mode = options.mode //1 模糊图片处理 
    if (mode == 1) {
      this.setData({
        mode:1,
        imgs: this.data.imgsBlurry,
        curImg: this.data.imgsBlurry[0]
      })
    } else { // 黑白图片上色
      this.setData({
        imgs: this.data.imgsBw,
        curImg: this.data.imgsBw[0]
      })
    }
    var token=wx.getStorageSync('token')
    if(!token){
      this.accessTokenFunc()
    }else{
      this.data.accessToken = token
      this.handlePic()
    }
  },
  bindUpload: function () {
    if(!app.IsLogin()){
      app.showToastMsg("请登录...")
      wx.switchTab({
        url: '/pages/mine/mine',
      })
      return
    }
    var that=this
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        console.log("res====", JSON.stringify(res))
        const tempFilePaths = res.tempFilePaths
        wx.navigateTo({
          url: '../golden/golden?mode='+that.data.mode+'&path='+tempFilePaths[0],
        })
      }
    })
  },
  init(res) {
    const width = res[0].width
    const height = res[0].height

    const canvas = res[0].node
    const ctx = canvas.getContext('2d')

    const dpr = wx.getSystemInfoSync().pixelRatio
    canvas.width = width * dpr
    canvas.height = height * dpr
    this.data.canvasWidth = width
    this.data.canvasHeight = height
    console.log("dpr===" + dpr)
    console.log("width===" + width)
    console.log("canvaswidth===" + canvas.width)
    console.log("height===" + height)
    ctx.scale(dpr, dpr)
    const renderLoop = () => {
      this.render(canvas, ctx)
      canvas.requestAnimationFrame(renderLoop)
    }
    canvas.requestAnimationFrame(renderLoop)
  },
  render(canvas, ctx) {
    if (this.x > this.data.canvasWidth || this.x < 0) return
    if(this.data.isBlackFirst){
      if (this.data.imageWidth > this.data.imageHeight) {
        var wh = this.data.imageWidth / this.data.imageHeight
        this.data.imageWidth = this.data.canvasWidth
        this.data.imageHeight = this.data.imageWidth / wh
      } else {
        var wh = this.data.imageWidth / this.data.imageHeight
        this.data.imageHeight =  this.data.canvasHeight
        this.data.imageWidth = this.data.imageHeight * wh
      }
      this.x = this.data.imageWidth / 2

      const img = canvas.createImage()
      img.onload = () => {
        console.log("img" + img)
        this._img = img
      }
      img.src = this.data.curImg
      const imgMap = canvas.createImage()
      imgMap.onload = () => {
        console.log("imgMap" + imgMap)
        this._imgMap = imgMap
      }
      imgMap.src = '../../images/middle.png'
      this.data.isBlackFirst=false
    }
    if (this.data.isHave && !this.data.isInit) {
      const imgTo = canvas.createImage()
      console.log("this.data.isInit==")
      imgTo.onload = () => {
        console.log("imgTo==" + imgTo)
        this._imgTo = imgTo
      }
      console.log("this.data.toPic==" + this.data.toPic)
      imgTo.src = this.data.toPic
      this.data.isInit = true
    }
    ctx.clearRect(0, 0, this.data.canvasWidth, this.data.canvasHeight)
    this.drawCar(ctx)
  },
  drawCar(ctx) {
    if (!this._img) return
    ctx.drawImage(this._img, 0, 0, this.data.imageWidth, this.data.imageHeight)
    ctx.save()
    ctx.lineWidth = 1
    ctx.strokeStyle = 'white'
    ctx.strokeRect(10, this.data.canvasHeight - 40, 80, 30)
    ctx.font = "16px cursive"
    ctx.fillStyle = "white"
    ctx.fillText('优化前', 30, this.data.canvasHeight - 20)

    if (this.data.isHave && this._imgTo) {
      var x = (this.x * this.data.originalWidth) / this.data.imageWidth
      ctx.drawImage(this._imgTo, x, 0, this.data.originalWidth, this.data.originalHeight, this.x, 0, this.data.imageWidth, this.data.imageHeight)
      ctx.restore()
      ctx.lineWidth = 1
      ctx.strokeStyle = 'white'
      ctx.strokeRect(this.x + 10, this.data.canvasHeight - 40, 80, 30)
      ctx.font = "16px cursive"
      ctx.fillStyle = "white"
      ctx.fillText('优化后', this.x + 30, this.data.canvasHeight - 20)

    }
    ctx.restore()
    ctx.beginPath()
    ctx.lineWidth = 3
    ctx.strokeStyle = "white"
    ctx.moveTo(this.x, 0)
    ctx.lineTo(this.x, this.data.imageHeight)
    ctx.stroke()
    var x = this.x - 15
    var y = (this.data.canvasHeight - 30) / 2
    ctx.drawImage(this._imgMap, x, y, 30, 30)
  },
  accessTokenFunc: function () {
    this.x = 0
    var that = this
    wx.cloud.callFunction({
      name: 'getBaiduToken',
      success: res => {
        console.log("==baiduAccessToken==" + JSON.stringify(res))
        that.data.accessToken = res.result.token
        wx.setStorageSync('token', res.result.token)
        that.handlePic()
      },
      fail: err => {
        wx.clearStorageSync("access_token")
        wx.showToast({
          icon: 'none',
          title: '调用失败,请重新尝试',
        })
        console.error('云函数baiduAccessToken调用失败：', err)
      }
    })
  },
  handlePic:function(){
    var that=this
    wx.getImageInfo({
      src: this.data.curImg,
      success: res => {
        that.data.originalWidth = that.data.imageWidth = res.width
        that.data.originalHeight = that.data.imageHeight = res.height
        that.onHandleImg(res.path)
        wx.createSelectorQuery()
          .select('#canvas')
          .fields({
            node: true,
            size: true,
          })
          .exec(that.init.bind(that))
      }
    })
  },
  onHandleImg: function (path) {
    var url = "https://aip.baidubce.com/rest/2.0/image-process/v1/colourize?access_token="
    if(this.data.mode==1){
      url="https://aip.baidubce.com/rest/2.0/image-process/v1/image_definition_enhance?access_token="
    }
   var that = this
    wx.getFileSystemManager().readFile({
      filePath: path,
      encoding: "base64",
      success: res => {
        var token = that.data.accessToken
        app.request.reqLoading(url + token, {
          "image": res.data
        }, function (appRes) {
          util.randomCode(4, '0123456789')
          var name =util.randomCode(4, '0123456789')+ '.png';
          that.data.name=name
          util.base64src(name,appRes.data.image).then(function (res) {
            console.log("base64src=====" + JSON.stringify(res))
            that.data.toPic = res
            that.data.isHave = true
          })
        }, "POST")
      },
      fail: res => {
        console.log("====getFileSystemManager=fail==" + JSON.stringify(res))
        wx.hideLoading()
      }
    })
  },
  onUnload: function() {
    util.onDeletePic(this.data)
  },
  bindTouch: function (e) {
    console.log(JSON.stringify(e))
    this.x = e.changedTouches[0].x
    console.log(e.changedTouches[0].x)
    console.log(e.changedTouches[0].y)
  },
  bindTap: function (e) {
    console.log(JSON.stringify(e))
    this.x = e.changedTouches[0].clientX
    console.log(e.changedTouches[0].clientX)
  },
  bindItem: function (e) {
    var index = e.currentTarget.dataset.index
    this.data.curImg = this.data.imgs[index]
    this.data.isInit = false
    this.data.isHave=false
    var that = this
    util.onDeletePic(this.data.name).then(res=>{
      wx.getImageInfo({
        src: this.data.curImg,
        success: res => {
          that.data.originalWidth = that.data.imageWidth = res.width
          that.data.originalHeight = that.data.imageHeight = res.height
          that.data.isBlackFirst=true
          that.x=0
          that.onHandleImg(res.path)
        }
      })
    })
  },
})